import config from "@/common/config";

export const format = (shijianchuo: string | number | Date, type = "yyyy-MM-dd hh:mm:ss") => {
    if (!shijianchuo) return "/";
    //shijianchuo是整数，否则要parseInt转换
    const time = new Date(shijianchuo);
    if (!time) return "/";
    const y = time.getFullYear();
    const m = time.getMonth() + 1;
    const d = time.getDate();
    const h = time.getHours();
    const mm = time.getMinutes();
    const s = time.getSeconds();
    const add0 = (m: number): string => {
        return m < 10 ? "0" + m : m + "";
    };
    return type
        .replace("yyyy", y + "")
        .replace("MM", add0(m))
        .replace("dd", add0(d))
        .replace("hh", add0(h))
        .replace("mm", add0(mm))
        .replace("ss", add0(s));
};
/**
 * 外部资源引入 js
 * @author duan 2017-01-19
 * @param  {[type]}   url      [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
export const loadJS = (url: string, id: string, callback: () => void) => {
    const heads = document.getElementsByTagName('head')
    let head
    if (heads && heads.length) {
        head = heads[0]
    } else {
        head = document.body
    }
    const script: any = document.createElement('script')

    script.type = 'text/javascript'
    script.id = id
    head.appendChild(script)
    script.onload = script.onreadystatechange = function () {
        if (!this.readyState || this.readyState === 'complete' || this.readyState === 'loaded') {
            if (callback) callback()
        }
    }
    script.src = url
}

export const mapLoad = (callback?: () => void) => {
    if ((window as any).AMap) {
        callback && callback()
    } else {
        ; (window as any)._AMapSecurityConfig = {
            securityJsCode: config.mapSign
        }
        loadJS(config.mapUrl, 'myMapJs', () => {
            callback && callback()
        })
    }
}

export const utilLogout = () => {
    localStorage.setItem("siteUserInfo", JSON.stringify({}));
    window.location.href = "/login"
}
export const getStorageUserInfo = () => {
    const userInfo = JSON.parse(localStorage.getItem('siteUserInfo') || "{}")
    return userInfo
}